<?php

namespace App\Morefun\Profile;

use App\Entities\Participant;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class AppUserCollector
{

    const USER_RECORD = 'users:recorded';
    protected $redis;

    public function gatherFromHttpReferer(Request $request)
    {
        $referer = $request->headers->get('referer');
        $query = parse_url($referer, PHP_URL_QUERY);

        if (!$query) {
            return;
        }

        $args = [];
        parse_str($query, $args);

        $this->syncToDatabase($args);
    }

    public function syncToDatabase(array $profile)
    {
        $openId = Arr::get($profile, 'uid');
        $username = Arr::get($profile, 'userName', Arr::get($profile, 'nickname'));
        $tenant_id = Arr::get($profile, 'TenantID', '');
        $uniqueid = md5(strtolower($tenant_id.$openId));
        if (empty($openId) ) {
            return;
        }
        $is_exist = $this->redis()->hget(self::USER_RECORD,$uniqueid);

        if($is_exist){
            return;
        }

        $participant = Participant::query()
            ->where('uniqueid', $openId)
            ->orWhere('uniqueid', $uniqueid)
            ->first();

        if (null == $participant) {
            $participant = new Participant();
            $participant->fill(['created_at' => date('Y-m-d H:i:s')]);
        }

        $participant->fill([
            'openid' => $openId,
            'source' => Arr::get($profile, 'SourceID', ''),
            'tenant_id' => $tenant_id,
            'username' => $username,
            'nickname' => Arr::get($profile, 'nickname', ''),
            'avatar' => Arr::get($profile, 'avatar', ''),
            'mobile' => Arr::get($profile, 'mobile', ''),
            'uid' => $openId,
            'uniqueid' => $uniqueid,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $participant->save();
        $this->redis()->hset(self::USER_RECORD,$uniqueid,1);
    }

    protected function redis()
    {
        if (!$this->redis) {
            $this->redis = Container::getInstance()->make('redis');
        }

        return $this->redis;
    }
}
